package com.yanghx.springtxjta.service;


import com.yanghx.springtxjta.dao.CustomerRepository;
import com.yanghx.springtxjta.domain.Customer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 客户service  注解方式
 *
 * @author yangHX
 * createTime  2019/8/7 22:28
 */
@Service
@Slf4j
public class CustomerServiceTxInAnnotation {

    @Resource
    private CustomerRepository customerRepository;

    /**
     * 使用注解事务的形式
     * import org.springframework.transaction.annotation.Transactional;
     *
     * @param customer 客户信息
     * @return 客户信息
     */
    @Transactional
    public Customer create(Customer customer) {
        log.info("CustomerService In Annotation create customer : {}", customer);
        if (null != customer.getId()) {
            throw new RuntimeException("用户已存在");
        }
        customer.setUserName("Annotation:" + customer.getUserName());
        customerRepository.save(customer);
        error();
        return customer;
    }


    private void error() {
        throw new RuntimeException("主动异常");
    }
}
